<template>
  <div class="base-editor">
    <WangToolbar
      border-b="1px solid #ccc"
      :editor="editorRef"
      :default-config="toolbarConfig"
      mode="default"
    />
    <WangEditor
      v-model="valueHtml"
      style="height: 200px; flex: 1; overflow-y: hidden"
      :default-config="editorConfig"
      mode="default"
      @on-created="handleCreated"
      @on-change="handleChange"
    />
  </div>
</template>

<script setup>
import { watch, shallowRef } from 'vue'
import '@wangeditor/editor/dist/css/style.css'
import {
  Editor as WangEditor,
  Toolbar as WangToolbar,
} from '@wangeditor/editor-for-vue'

import api from './api'

const editorRef = shallowRef()
const toolbarConfig = { excludeKeys: 'fullScreen' }
const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      customUpload,
    },

    uploadVideo: {
      customUpload,
    },
  },
}

async function customUpload(file, insertFn) {
  const params = {
    code: 0,
    files: file,
  }

  const { code, data } = await api.uploadFile(params)

  if (code === 200) {
    const url = `${data.domain}${data.url}`
    insertFn(url)
  }
}

const props = defineProps(['value'])
const emit = defineEmits(['update:value'])

const valueHtml = ref('')

watch(
  () => props.value,
  () => {
    if (props.value !== valueHtml.value) {
      valueHtml.value = props.value
    }
  },
  {
    immediate: true,
  }
)

const handleCreated = (editor) => {
  editorRef.value = editor
}

const handleChange = () => {
  if (valueHtml.value !== '<p><br></p>') {
    emit('update:value', valueHtml.value)
  }
}
</script>

<style lang="scss" scoped></style>
